package com.cracker.websocket.server.task;

import com.cracker.websocket.server.entity.UserEntity;
import com.cracker.websocket.server.service.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.IOException;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
@EnableScheduling
@Slf4j
public class HeartbeatCheckTask {
    @Autowired
    private SessionService sessionService;

    //    @Scheduled(cron = "0/5 * * * * ?")
    //或直接指定时间间隔，例如：5秒
    @Scheduled(fixedRate = 4000)
    private void configureTasks() {
        new HeartbeatCheck(sessionService).start();
    }

    class HeartbeatCheck extends Thread {
        private SessionService sessionService;

        public HeartbeatCheck(SessionService sessionService) {
            this.sessionService = sessionService;
        }

        @Override
        public void run() {
            // 遍历链接,判断是否超时
            log.info("心跳检查");
            AtomicInteger count = new AtomicInteger();
            AtomicInteger timeout = new AtomicInteger();
            sessionService.getOnlineSession().forEach((id, session) -> {
                count.getAndIncrement();
                Date freshTime = (Date) session.getUserProperties().get("freshTime");
                long offset = (new Date().toInstant().getEpochSecond()) - freshTime.toInstant().getEpochSecond();
                if (offset > 10) {
                    UserEntity userEntity = (UserEntity) session.getUserProperties().get("user");
                    timeout.getAndIncrement();
                    log.warn("超时：{}秒", offset);
                    try {
                        sessionService.getOnlineSession().remove(userEntity.getId());
                        session.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            log.info("心跳检查完毕,总链接:{}个 超时:{}个", count, timeout);
        }
    }
}